package sit.mycatalog.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sit.mycatalog.ejb.sess.ItemSess;
import sit.mycatalog.jpa.Item;
import sit.mycatalog.util.ConfigConstant;
import sit.mycatalog.util.SessLookup;

/**
 * Servlet implementation class ItemImageService
 */
@WebServlet("/images/item/*")
public class ItemImageService extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ItemImageService() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String strItem = request.getRequestURI();
		strItem = strItem.replaceFirst(request.getContextPath() + "/images/item/", "");
//		System.out.println(strItem);

		FileInputStream fin = null;

		try {
			ItemSess sessItem = SessLookup.getItemSess();
			Item entItem = sessItem.getItem(strItem);
			
			File fileImage = new File(ConfigConstant.ITEM_IMAGE_PATH + entItem.getImgpath());
			
			if((entItem.getImgpath() != null) && (!entItem.getImgpath().equals(""))) {
				String strExtension = entItem.getImgpath().substring(entItem.getImgpath().lastIndexOf("."), entItem.getImgpath().length()).toLowerCase();
				response.setContentType("image/" + strExtension);
			} else {
				response.setContentType("image/jpeg");
			}
			
			if(!fileImage.exists()) {
				fileImage = new File(ConfigConstant.IMAGE_PATH + "no_image.jpg");
			}

			fin = new FileInputStream(fileImage.getAbsolutePath());

			OutputStream out = response.getOutputStream();
			response.setContentLength((int) fileImage.length());

			byte[] buffer = new byte[4096];
			int readed = -1;

			while ((readed = fin.read(buffer)) != -1) {
				out.write(buffer, 0, readed);
			}

			out.flush();

		} catch (Exception ex) {
			throw new ServletException("doGet(): " + ex.getMessage(), ex);
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (Exception ex) {
					throw new ServletException("doGet(): " + ex.getMessage(), ex);
				}
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
